package main

import (
	"context"
	"errors"
	"fmt"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"google.golang.org/grpc/metadata"
	"net"
	pd "ycc_grpc_study/hello-server/proto"
)

type server struct {
	pd.UnimplementedSayHelloServer
}

func (s *server) SayHello(ctx context.Context, req *pd.HelloRequest) (*pd.HelloResponse, error) {
	// token validate start
	// 从客户端获取数据
	mete, ok := metadata.FromIncomingContext(ctx)
	fmt.Println("client 传的数据", mete)
	if !ok {
		return nil, errors.New("会话结束")
	}
	var appid string
	var appkey string
	if v, ok := mete["appid"]; ok {
		appid = v[0]
	}
	if v, ok := mete["appkey"]; ok {
		appkey = v[0]
	}

	if appid != "123456" || appkey != "123456" {
		return nil, errors.New("会话错误")
	}
	// token validate end
	fmt.Println("Hello World" + req.RequestName)
	return &pd.HelloResponse{ResponseMsg: "Hello World" + req.RequestName}, nil
}

func main() {
	// TSL 认证
	// 自签名证书文件和私钥文件
	//credent, _ := credentials.NewServerTLSFromFile("D:\\project_go\\src\\ycc_grpc_study\\key\\test.pem", "D:\\project_go\\src\\ycc_grpc_study\\key\\test.key")
	// 开启端口
	listen, err := net.Listen("tcp", ":9090")
	if err != nil {
		fmt.Println("net listen err:", err)
		return
	}
	// 创建 grpc 服务
	//grpcServer := grpc.NewServer(grpc.Creds(credent))
	grpcServer := grpc.NewServer(grpc.Creds(insecure.NewCredentials()))
	// 在grpc服务端中去注册我们自己编写的服务
	pd.RegisterSayHelloServer(grpcServer, &server{})

	// 启动服务
	err = grpcServer.Serve(listen)
	if err != nil {
		fmt.Println("net listen err:", err)
		return
	}
}
